<?php
/**
 * 心愿模型类
 */

class CrowdfundingModel extends Model
{
    private $crowdfunding_id;

    const REVIEW = 0;
    const PASSED = 1;
    const NOT_PASS = 2;
    const SUCCESS = 3;
    const FAILURE = 4;

    /**
     * 构造函数
     * @author 姜伟
     * @todo 构造函数
     */
    public function __construct($crowdfunding_id=0)
    {
        parent::__construct();
        $this->crowdfunding_id = $crowdfunding_id;
    }

    public function getCrowdfundingNum($where){
        return $this->where($where)->count();
    }

    public function addCrowdfunding($arr){
        if(!is_array($arr)) return false;
        $arr['addtime'] = time();
        return $this->add($arr);
    }

    //查询心愿表的某个字段
    public function getCrowdfundingField($where,$field){
        return $this->where($where)->getField($field);
    }

    public function getCrowdfundingIFields($where,$field,$group=''){
        return $this->where($where)->group($group)->getField($field,true);
    }


    public function getCrowdfundingInfo($where){
        return $this->where($where)->find();
    }

    //获取心愿剩余天数
    public function getCfLeftDay($cf_id){
        $cf = $this->getCrowdfundingInfo($cf_id);
        $now_date = strtotime(date('Ymd'));
        $left_time = strtotime($cf['end_time']) - $now_date;
        if($left_time <= 0) $left_time = 0;
        $left_day = $left_time / 86400;
        return $left_day;
    }

    //状态变更．
    public function setStatus($cf_id,$arr){
        if (!$cf_id) return false;
        $cf_info = self::getCrowdfundingInfo('crowdfunding_id ='.$cf_id);
        $title = D('Post')->where('post_id ='.$cf_info['post_id'])->getField('title');
        if($arr['status'] == CrowdfundingModel::PASSED){
            $post_obj = new PostModel();
            $post_obj->where('post_id ='.$cf_info['post_id'])->save(array('review'=> 1));
        }
        $r = $this->where('crowdfunding_id ='.$cf_id)->save($arr);
        if($r){
            //消息通知发帖人
            $content = $this->getStatusMessage($arr['status'], $title);
            D('Message')->addMessage($cf_info['post_id'], 4, 0, $cf_info['user_id'], $content, $content, '/FrontChannel/post_detail/post_id/'.$cf['post_id']);
        }
        return $r;
    }

    private function getStatusMessage($status, $title){
        $arr = array(
            self::PASSED => '恭喜，您的心愿《'.$title.'》已通过审核',
            self::NOT_PASS => '抱歉，您的心愿《'.$title.'》未通过审核',
            self::SUCCESS => '恭喜，您的心愿《'.$title.'》在规定时间内达到指定金额，心愿成功！',
            self::FAILURE => '对不起，您的心愿《'.$title.'》在规定时间内未达到指定金额，心愿失败！',
            );
        return $arr[$status];
    }


    public function getCfByPost($post_id){
        return $this->where('post_id ='.$post_id)->find();
    }


    public function support($cf_id, $support_money){
        $this->where('crowdfunding_id ='.$cf_id)->setInc('support_num');
        $this->where('crowdfunding_id ='.$cf_id)->setInc('now_money', $support_money);
    }

    public function getCrowdfundingList($field =null,$where, $order='addtime desc'){

        return $this->field($field)->where($where)->order($order)->limit()->select();
    }

    public function getCrowdfundingAllList($field =null,$where, $order='addtime desc'){

        return $this->field($field)->where($where)->order($order)->limit(10000000)->select();
    }

    public function getListData($cf_list){
        foreach ($cf_list as $k => $v) {
            //帖子信息
            $post_obj = new PostModel();
            $post_info = $post_obj->getPostInfo('post_id ='.$v['post_id']);
            $cf_list[$k]['title'] = $post_info['title'];
            $cf_list[$k]['is_featured'] = $post_info['is_featured'];
            //频道名称．
            $channel_obj = new ChannelModel();
            $cf_list[$k]['channel_name'] = $channel_obj->getChannelField($post_info['channel_id'],'channel_name');
            //发布人
            $user = M('Users')->where('user_id ='.$v['user_id'])->find();
            $cf_list[$k]['nickname'] = $user['nickname'];
            //时间
            $cf_list[$k]['acp_time'] = date('Y-m-d H:i:s', $v['addtime']);
            $cf_list[$k]['acp_pass_time'] = date('Y-m-d H:i:s', strtotime($v['pass_time']));
            $cf_list[$k]['acp_end_time'] = date('Y-m-d H:i:s', strtotime($v['end_time']));
            //状态
            $url = '';
            $url_support = '';
            $url_comment_list = '';
            if ($v['status'] == self::REVIEW) {
                $url = 'post_review_cf_detail';
            }elseif ($v['status'] == self::PASSED){
                $url = 'post_passed_cf_detail';
                $url_support = 'passed_cf_support';
                $url_comment_list = 'get_passed_cf_comment_list';

            }elseif ($v['status'] == self::SUCCESS){
                $url = 'post_success_cf_detail';
                $url_support = 'success_cf_support';
                $url_comment_list = 'get_success_cf_comment_list';

            }elseif ($v['status'] == self::FAILURE){
                $url = 'post_failure_cf_detail';
                $url_support = 'failure_cf_support';
                $url_comment_list = 'get_failure_cf_comment_list';
            }

            if($v['is_del']){
                $url = 'post_del_cf_detail';
                $url_support = 'del_cf_support';
                $url_comment_list = 'get_del_cf_comment_list';
            }

            $cf_list[$k]['url_detail'] = $url;
            $cf_list[$k]['url_support'] = $url_support;
            $cf_list[$k]['url_comment_list'] = $url_comment_list;

        }
        return $cf_list;
    }

    /**
     * 心愿退款
     * @param $cf_id
     * @return float|int
     */
    public function cf_refund($cf_id){
        //所有的支持用户
        $cf_support_obj = new CfSupportModel();
        $cf_support_list = $cf_support_obj->getCfSupportAllList($cf_id);
        $success = 0;
        foreach ($cf_support_list as $k => $v){
            //找出对应心愿信息
            $cf_obj = new CrowdfundingModel();
            $cf_info = $cf_obj->getCrowdfundingInfo('crowdfunding_id ='.$v['crowdfunding_id']);
            $account_obj = new AccountModel();
            $success += $account_obj->addAccount($v['user_id'],AccountModel::CF_REFUND,$v['support_money'],'心愿失败退款',$v['crowdfunding_id'],$cf_info['post_id']);
            if($success){
                $cf_support_obj->setRefund($v['cf_support_id']);
            }
        }
        return $success;
    }

    /**
     * 心愿结束
     * 可以控制减少资金
     */
    public function cf_end(){
        $cf_obj = new CrowdfundingModel();
        //找出所有进行中并结束时间时间小于等于当前时间的心愿
        $cf_list = $cf_obj->getCrowdfundingAllList('','status ='.self::PASSED.' and end_time <='.date('Ymd',time()));
        foreach ($cf_list as $k => $v){
            if($v['now_money'] < $v['goal_money']){
                $cf_obj->setStatus($v['crowdfunding_id'],array('status' => CrowdfundingModel::FAILURE));
            }else{
                $success = $cf_obj ->setStatus($v['crowdfunding_id'],array('status' => CrowdfundingModel::SUCCESS));
                if($success){

                    //wangtao 2017.9.15 -start

                    //根据用户的头衔来扣除分成
                    $as_moneyes = D('UserTitle')->getTitlePostCash($v['user_id']);
                    if($as_moneyes){
                        //根据用户的头衔来扣除分成
                        $as_moneyes = intval($as_moneyes[0]['title_rates']);
                    }else{
                        //根据当前频道来扣除分成
                        $as_moneyes = D('Post')->getPostReatts($v['post_id'])[0]['channel_rates'];
                    }
                    $as_money = round($v['now_money'] * $as_moneyes / 100,2);
                    $lz_money = $v['now_money'] - $as_money;
                    //wangtao 2017.9.15 -end

                    $account_obj = new AccountModel();
                    $account_obj->addAccount($v['user_id'],AccountModel::CF_SUCCESS,$lz_money,'心愿成功奖金',$v['crowdfunding_id'],$v['post_id']);
                }
            }
        }
    }

    public function delPost($post_id){
        return $this->where('post_id ='.$post_id)->save(array('is_del' => 1));
    }


    public function resPost($post_id){
        return $this->where('post_id ='.$post_id)->save(array('is_del' => 0));
    }
}
